package com.tramy.data.export.aop;

import com.tramy.data.export.annotation.DataSourceChoice;
import com.tramy.data.export.datasource.DatabaseContextHolder;
import com.tramy.data.export.datasource.DatabaseType;
import com.tramy.data.export.exception.DataSourceChoiceException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

/**
 * Created by honway on 2016/11/7.
 */
//@Component
//@Aspect
public class AspectJDataSourceChoice {

    @Pointcut("execution(public * com.tramy.data.export.mapper.*.*(..))")
    public void aspectJMethods(){}

    /**
     * spring aop代理了mybatis interfact之后,拿不到类上的注解
     * 所以,这个暂时是没用
     * @param joinPoint
     * @throws DataSourceChoiceException
     */
    @Before("aspectJMethods()")
    public void choiceDataSource(JoinPoint joinPoint) throws DataSourceChoiceException {
        Class<?> aClass = joinPoint.getTarget().getClass();
        if (aClass.isAnnotationPresent(DataSourceChoice.class)) {
            DataSourceChoice dataSourceChoice = aClass.getDeclaredAnnotation(DataSourceChoice.class);
            DatabaseType value = dataSourceChoice.value();
            if (value == DatabaseType.firehome
                    || value == DatabaseType.pinshang
                    || value == DatabaseType.tramygs) {
                DatabaseContextHolder.setDatabaseType(value);
                System.out.println("开始根据注解设置数据源");
            } else {
                throw new DataSourceChoiceException("@DataSourceChoice注解value值不能为空.", new DataSourceChoiceException());
            }
        }
    }
}
